<?php

namespace App\Http\Middleware;

use App\Services\LogService;
use App\Services\PerformanceService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class PerformanceMonitoringMiddleware
{
    protected $logService;
    protected $performanceService;

    public function __construct(LogService $logService, PerformanceService $performanceService)
    {
        $this->logService = $logService;
        $this->performanceService = $performanceService;
    }

    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $startTime = microtime(true);
        $startMemory = memory_get_usage(true);

        // 监控数据库查询
        $this->performanceService->monitorDatabaseQueries();

        // 处理请求
        $response = $next($request);

        // 计算性能指标
        $endTime = microtime(true);
        $endMemory = memory_get_usage(true);
        
        $duration = ($endTime - $startTime) * 1000; // 毫秒
        $memoryUsed = $endMemory - $startMemory;

        // 记录API请求日志
        $this->logService->logApiRequest(
            $request->method(),
            $request->fullUrl(),
            $this->getRequestData($request),
            $response->getStatusCode(),
            $duration
        );

        // 记录性能指标
        $this->logService->logPerformance('api_request', $duration, [
            'method' => $request->method(),
            'url' => $request->fullUrl(),
            'memory_used' => $memoryUsed,
            'memory_used_mb' => round($memoryUsed / 1024 / 1024, 2),
            'status_code' => $response->getStatusCode(),
        ]);

        // 添加性能头信息
        $response->headers->set('X-Response-Time', $duration . 'ms');
        $response->headers->set('X-Memory-Usage', round($memoryUsed / 1024 / 1024, 2) . 'MB');

        return $response;
    }

    /**
     * 获取请求数据（过滤敏感信息）
     */
    private function getRequestData(Request $request): array
    {
        $data = $request->all();
        
        // 过滤敏感字段
        $sensitiveFields = ['password', 'token', 'secret', 'key', 'code'];
        
        foreach ($sensitiveFields as $field) {
            if (isset($data[$field])) {
                $data[$field] = '***';
            }
        }
        
        return $data;
    }
}